#!/usr/bin/python
import time
import urllib
import os
import base64

# Configuration
ping_time = 60
computer_id = None
ping_url = None

is_active = False
while True:
	while True:
		f = open("/Library/StartupItems/mac-recover/mac-recover.conf")
		for line in f:
			if line.strip()[0:8] == "ping_url" and line.find("=") is not -1:
				ping_url = line[line.find("=") + 1:].strip()
			elif line.strip()[0:11] == "computer_id" and line.find("=") is not -1:
				computer_id = line[line.find("=") + 1:].strip()
		if computer_id is not None and ping_url is not None and computer_id is not "" and ping_url is not "":
			break
		else:
			time.sleep(ping_time)
	try:
		data = urllib.urlopen(ping_url, data = urllib.urlencode({"action": "ping", "computer_id": computer_id}), proxies = {}).read()
		if data.count("|active|") is not 0:
			is_active = True
			os.spawnl(os.P_WAIT, "/Library/StartupItems/mac-recover/qt-capture", "qt-capture")
			os.spawnlp(os.P_WAIT, "screencapture", "screencapture", "-x", "/Library/StartupItems/mac-recover/Images/screen-" + str(time.time()) + ".png")
			for f in os.listdir("/Library/StartupItems/mac-recover/Images"):
				if f == ".DS_Store":
					pass
				else:
					image = open("/Library/StartupItems/mac-recover/Images/" + f, "rb")
					urllib.urlopen(ping_url, data = urllib.urlencode({"action": "upload", "computer_id": computer_id, "file_name": f, "file_contents": base64.b64encode(image.read())}))
					image.close()
					os.remove("/Library/StartupItems/mac-recover/Images/" + f)
		else:
			is_active = False
			for f in os.listdir("/Library/StartupItems/mac-recover/Images"):
				if f == ".DS_Store":
					pass
				else:
					os.remove("/Library/StartupItems/mac-recover/Images/" + f)
	except:
		if is_active is True:
			os.spawnl(os.P_WAIT, "/Library/StartupItems/mac-recover/qt-capture", "qt-capture")
			os.spawnlp(os.P_WAIT, "screencapture", "screencapture", "-x", "/Library/StartupItems/mac-recover/Images/screen-" + str(time.time()) + ".png")
		else:
			pass
	time.sleep(ping_time)